#include "NameServer.h"

NameServer::NameServer( Printer &prt, unsigned int numVendingMachines, unsigned int numStudents )
: myPrinter(prt), myNumVendingMachines(numVendingMachines), myNumStudents(numStudents), currentRegistered(0)
{
    // initialize students
    myStudentList.resize(numStudents);
    for(unsigned int i=0; i<myStudentList.size(); i++)
    {
        myStudentList.at(i) = i % numVendingMachines;
    }
    
    // initialize empty list of vending machines
    myVendingMachines = new VendingMachine*[numVendingMachines]();
}

NameServer::~NameServer()
{
	delete[] myVendingMachines;
}

void NameServer::main()
{
    myPrinter.print(Printer::NameServer, 'S');
    for(;;)
    {
        _Accept(~NameServer)
        {
            break;
        }
        or
        _When (currentRegistered < myNumVendingMachines) _Accept(VMregister)
        {
            myPrinter.print(Printer::NameServer, 'R', currentRegistered - 1);
        }
        or 
        _When (currentRegistered == myNumVendingMachines) _Accept(getMachine)
        { }
        or 
        _When (currentRegistered == myNumVendingMachines) _Accept(getMachineList)
        { }
    }
    
    myPrinter.print(Printer::NameServer, 'F');    
}


void NameServer::VMregister( VendingMachine *vendingmachine )
{
    myVendingMachines[currentRegistered++] = vendingmachine;
}

VendingMachine *NameServer::getMachine( unsigned int id )
{
    unsigned int vend_id = myStudentList.at(id);
    myPrinter.print(Printer::NameServer, 'N', id, vend_id);
    VendingMachine* vendingMachine = myVendingMachines[vend_id];
    myStudentList.at(id) = (vend_id+1)%myNumVendingMachines;
    return vendingMachine;
}

VendingMachine **NameServer::getMachineList()
{
    return myVendingMachines;
}
